<template>
  <!-- 地图展示 -->
  <div id="map">
    <p id="currentPoint">
      <i class="el-icon-location"></i>
      {{ currentPoint.lat?currentPoint.lat:"-" }}, {{ currentPoint.lng?currentPoint.lng:"-" }}
    </p>
  </div>
</template>
<script>
  import { Loading } from 'element-ui';
  import { wgs84ToGcj02 } from '@/api/common/common';
  import * as turf from '@turf/turf';
  require('math');

  var loadingInstance;
  var airspaceLayer = null; // 空域图层
  var pointLayer = null;  // 航路点|机场图层
  var lineLayer = null; // 航线图层
  // var sector;
  var markerIcon = L.icon({
    iconUrl: require('@/assets/images/marker.png'),
    iconSize: [12, 12],
    // iconAnchor: [22, 94],
    // popupAnchor: [-3, -76],
    // shadowUrl: 'my-icon-shadow.png',
    // shadowSize: [68, 95],
    // shadowAnchor: [22, 94]
  });
  var fairwayLayer;
  var drawnItems;
  export default {
    name: 'MapDetail',
    data() {
      return {
        airspaceInfo:{},
        airspacePointList:[],
        focusAnum:"", // 聚焦的飞行器
        
        // 注册号标签显示隐藏
        isShow:true,

        // 地图
        map:null,
        layerGroupList:[],  // 空域列表
        currentPoint:{
          lng:null,
          lat:null
        },
        movingObj:{}, // 当前接收到的飞行器移动轨迹集合
      }
    },
    mounted(){
      this.$nextTick(()=>{
        // var normalm =  L.esri.tiledMapLayer({
        //   url: 'https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer'
        // });
        // var satelliteImgm = L.tileLayer.chinaProvider('TianDiTu.Satellite.Map');
        // var satelliteImga = L.tileLayer.chinaProvider('TianDiTu.Satellite.Annotion');
        var normalm = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
          maxZoom: 18,
          minZoom: 4
        });
        var satelliteImgm = L.tileLayer.chinaProvider('GaoDe.Satellite.Map');
        var satelliteImga = L.tileLayer.chinaProvider('GaoDe.Satellite.Annotion');
        var satellite = L.layerGroup([satelliteImgm, satelliteImga]);
        var normal = L.layerGroup([normalm]);
        let layerName = {
          "卫星地图":satellite,
          "普通地图":normalm
        }
        // var centerLatLng = wgs84ToGcj02(29.7466, 106.8056);
        this.map = L.map("map",{
          // center:centerLatLng,
          center:[40.2646, 116.3991],
          zoom:8,
          // layers:[satellite, normalm],
          preferCanvas:true,
          zoomControl:false,
          attributionControl:false,
          inertia:false,
          trackResize:true
        });
        L.control.layers(layerName).addTo(this.map);
        normalm.addTo(this.map);
        // 比例尺
        L.control.scale({imperial:false}).addTo(this.map);
        // 缩放
        L.control.zoom().setPosition("topleft").addTo(this.map);
        this.map.setView([40.2646, 116.3991], 8)

        // this.initWebsocket();
        
        // 绘制扇形
        // this.drawSector([31.59586, 120.2995], 0.02, -60, 45, 800);

        // 监听地图点击事件
        this.map.on('click', (e)=>{
          console.log(e)
          this.$emit("getPointByMapClick", {
            lat:e.latlng.lat,
            lng:e.latlng.lng
          })
        })

        // 监听地图鼠标移动事件
        this.map.on('mousemove', (e)=>{
          this.currentPoint.lng = (e.latlng.lng < 0 ? 'W ' : 'E ') + this.D2Dms(e.latlng.lng);
          this.currentPoint.lat = (e.latlng.lat < 0 ? 'S ' : 'N ') + this.D2Dms(e.latlng.lat);
        })

        // 监听地图移动事件
        // this.map.on('move', (e)=>{
        // })

        // 监听地图缩放事件
        this.map.on('zoom', (e)=>{
          // if(e.target._zoom <= 7 && this.isShow){
          //   this.isShow = false;
          //   document.getElementsByClassName("iconLabel").forEach(item=>{
          //     item.style.display = "none";
          //   })
          // }
          // if(e.target._zoom > 7 && !this.isShow){
          //   this.isShow = true;
          //   document.getElementsByClassName("iconLabel").forEach(item=>{
          //     item.style.display = "block";
          //   })
          // }
        })

        window.onresize = ()=>{
          this.map.invalidateSize(true);
          // this.map.fitBounds([
          //   [31.59102002701019, 120.30037886225469],
          //   [31.589045999457486, 120.30016433385363],
          //   [31.589064277682226, 120.30222380650356],
          //   [31.59586, 120.2995]
          // ]);
        }
      })
    },
    methods:{
      // 空域数据初始化
      initAirspaceList(airspaceInfo){
        this.airspaceInfo = airspaceInfo;
        this.airspacePointList = airspaceInfo.spacePoints;
        this.layerGroupList = [];
        this.clearAllLayer();
        let arr = [];
        if(airspaceInfo.spacePoints.length){
          switch (airspaceInfo.spaceShape) {
            case 1:
              // 多边形
              this.airspacePointList.map((vo, index)=>{
                arr.push([vo.pLat, vo.pLng]);
                if(index == this.airspacePointList.length-1){
                  this.layerGroupList.push(L.polygon(arr, {color:"red"}));
                }
                if(index == this.airspacePointList.length-1){
                  airspaceLayer = L.layerGroup(this.layerGroupList);
                  this.$nextTick(()=>{
                    airspaceLayer.addTo(this.map);
                    this.map.setView([this.airspacePointList[0].pLat, this.airspacePointList[0].pLng], 8);
                  })
                }
              })
              break;
            case 2:
              // 圆形
              let radius = Number(this.airspacePointList[0].pRadius) * 1000;
              this.layerGroupList.push(L.circle([this.airspacePointList[0].pLat, this.airspacePointList[0].pLng], {
                color: 'red',
                // fillColor:'transparent',
                radius: radius
              }).bindPopup("<div style='padding:5px;'><b>"+this.airspacePointList[0].spaceName+"(半径:"+this.airspacePointList[0].pRadius+"km)</b><br/>"+(this.airspacePointList[0].pLat<0?'S ':'N ')+this.D2Dms(this.airspacePointList[0].pLat)+","+(this.airspacePointList[0].pLng<0?'W ':'E ')+this.D2Dms(this.airspacePointList[0].pLng)+"</div>"));
              airspaceLayer = L.layerGroup(this.layerGroupList);
              this.$nextTick(()=>{
                airspaceLayer.addTo(this.map);
                this.map.setView([this.airspacePointList[0].pLat, this.airspacePointList[0].pLng], 9);  
              })
              break;
            case 3:
              // 扇形
              var points = this.getPoints([this.airspacePointList[0].pLat, this.airspacePointList[0].pLng], this.airspacePointList[0].pRadius, this.airspacePointList[0].pAngleStart, this.airspacePointList[0].pAngleEnd, 800);
              points[points.length] = points[0];
              this.layerGroupList.push(L.polygon(points, {color:"red"}))
              airspaceLayer = L.layerGroup(this.layerGroupList);
              this.$nextTick(()=>{
                airspaceLayer.addTo(this.map);
                this.map.setView([this.airspacePointList[0].pLat, this.airspacePointList[0].pLng], 9);
              })
              break;
          }
        }
      },

      // 机场|航路点数据初始化
      initAirportOrPointData(info, type){
        this.clearAllLayer();
        if(info.lng && info.lat){
          let iconUrl = "", iconSize = [];
          switch (type) {
            case 1:
              // 机场
              iconUrl = require("@/assets/images/airport.png");
              iconSize = [20, 20];
              break;
            case 2:
              // 野外起降点
              iconUrl = require("@/assets/images/airportField.png");
              iconSize = [20, 20];
              break;
            case 3:
              // 临时起降点
              iconUrl = require("@/assets/images/airportTmp.png");
              iconSize = [20, 20];
              break;
            default:
              // 航路点
              iconUrl = require('@/assets/images/airpoint.png');
              iconSize = [18, 22];
              break;
          }
          let pointIcon = L.icon({
            iconUrl: iconUrl,
            iconSize: iconSize
          });
          let marker = L.marker([info.lat, info.lng], {icon: pointIcon}).bindTooltip(info.name)
          .bindPopup("<div style='padding:5px;'><b>"+info.name+"</b><br/>"+info.latstr+","+info.lngstr+"</div>");
          pointLayer = L.layerGroup([marker]);
          pointLayer.addTo(this.map);
          this.map.setView([info.lat, info.lng], 7);
        }
      },

      // 航线数据初始化
      initAirlineData(lineList){
        this.clearAllLayer();
        let linePointArr = [], lineArr = [], polyline = null,linePointLayer;
        let pointIcon = L.icon({
          iconUrl: require('@/assets/images/marker.png'),
          iconSize: [8, 8]
        });
        var bufferStyle = { //航线缓冲区
          weight: 20,
          color: '#FF7C7A'
        };
        drawnItems = new L.FeatureGroup();
        this.map.addLayer(drawnItems);
        lineList.map((vo, index)=>{
          lineArr.push([vo.pLat, vo.pLng]);
          var divHtml = '<span style="padding: 5px;height: 24px;\n' +
              '    text-align: center;\n' +
              '    line-height: 24px;\n' +
              '    border-radius: 4px;border: 2px solid #fff;\n' +
              '    margin-left: -12px;\n' +
              '    white-space:nowrap;background:#00E736;color:#fff;font-size:12px;">' +
              '<span style=" width: 0;\n' +
              '    height: 0;\n' +
              '    border: 2px solid #fff;\n' +
              '    position: absolute;\n' +
              '    margin-left: -6px;\n' +
              '    left: 50%;\n' +
              '    top: 24px;border-top-color: #00E736"></span>'+vo.name+'</span>';
          const myDivIcon = L.divIcon({
            html: divHtml,
            className: 'my-div-icon',
            iconAnchor: [5, 30]
          });
          let marker = L.marker([vo.pLat, vo.pLng], {icon: myDivIcon});
          marker.bindTooltip(vo.name)
          .bindPopup("<div style='padding:5px;'><b>"+vo.name+"</b><br/>经纬度:"+vo.pLatDis+","+vo.pLngDis+"</div>");
          linePointArr.push(marker)

          if(index == lineList.length-1){
            // pointLayer = L.layerGroup(linePointArr);
            // pointLayer.addTo(this.map);
            polyline = L.polyline(lineArr, {color:"red"});
            //线操作
            polyline.on({
              //mouseover：移入
              mouseover: ((e) => {
                var layer = e.target;
                layer.setStyle({
                  weight: 5,
                  color: '#00E736',
                });
                if (!L.Browser.ie && !L.Browser.opera) {
                  layer.bringToFront();
                  linePointLayer = L.layerGroup(linePointArr);
                  linePointLayer.addTo(this.map);
                }
              }),
              //mouseout：移出
              mouseout: ((e) => {
                var layer = e.target;
                layer.setStyle({
                  weight: 2,
                  opacity: 1,
                  color: 'red'
                });
                if(linePointLayer){
                  this.map.removeLayer(linePointLayer);
                }
              })
            });
            this.layerGroupList.push(polyline);
            lineLayer = L.layerGroup(this.layerGroupList);
            lineLayer.addTo(this.map);
            //添加缓冲区
            this.createBufferedRoute(polyline,bufferStyle);
            this.map.fitBounds(polyline.getBounds());
          }
        })
      },

      // 创建航线缓冲区
      createBufferedRoute(polyline, bufferStyle) {
        if (fairwayLayer) {
          // 这样子把航道图层删掉才能防止出现连续绘制样式叠加的情况（比如航道越画透明度越深）
          this.map.removeLayer(fairwayLayer);
        }
        const buffered = turf.buffer(polyline.toGeoJSON(), bufferStyle.weight, {
          units: 'meters'
        });
        // console.log(buffered, 'buffered');
        // console.log(drawnItems, 'drawnItems');
        fairwayLayer = L.geoJSON(buffered, {
          style: function (feature) {
            return {
              color: bufferStyle.color,
              fillOpacity: 0.3,
              dashArray: '5,5',
              interactive: false
            };
          }
        }).addTo(drawnItems);
      },

      // 清除图层
      clearAllLayer(){
        if(airspaceLayer) this.map.removeLayer(airspaceLayer);
        if(pointLayer) this.map.removeLayer(pointLayer);
        if(lineLayer) this.map.removeLayer(lineLayer);
      },

      /* 
       * 点击绘制
       * @param shape 空域形状
       * @param pointNum 当前点位个数
       * @param obj 点位信息
      */
      drawLayerByClick(shape, pointNum, obj){
        this.clearAllLayer();
        switch (shape) {
          case 1:
            // 多边形
            if(pointNum > 2){
              this.layerGroupList = [];
              let arr = [];
              this.airspacePointList.map((vo, index)=>{
                arr.push([vo.pLat, vo.pLng]);
                if(index == this.airspacePointList.length-1){
                  this.layerGroupList.push(L.polygon(arr, {color:"red"}));
                }
                if(index == this.airspacePointList.length-1){
                  airspaceLayer = L.layerGroup(this.layerGroupList);
                  airspaceLayer.addTo(this.map);
                }
              })
            }else{
              var marker = L.marker([obj.pLat, obj.pLng],{icon:markerIcon}).bindTooltip(Number(obj.pLat).toFixed(6)+", "+Number(obj.pLng).toFixed(6));
              this.layerGroupList.push(marker);
              airspaceLayer = L.layerGroup(this.layerGroupList);
              airspaceLayer.addTo(this.map);
            }
            break;
          case 2:
            // 圆形
            let radius = Number(this.airspacePointList[0].pRadius) * 1000;
            if(pointNum == 1){
              this.layerGroupList.push(L.circle([this.airspacePointList[0].pLat, this.airspacePointList[0].pLng], {
                color: 'red',
                // fillColor:'transparent',
                radius: radius
              }));
              airspaceLayer = L.layerGroup(this.layerGroupList);
              airspaceLayer.addTo(this.map);
            }
            break;
          case 3:
            // 扇形
            if(pointNum > 0){
              var points = this.getPoints([this.airspacePointList[0].pLat, this.airspacePointList[0].pLng], this.airspacePointList[0].pRadius, this.airspacePointList[0].pAngleStart, this.airspacePointList[0].pAngleEnd, 800);
              points[points.length] = points[0];
              this.layerGroupList.push(L.polygon(points, {color:"red"}))
              airspaceLayer = L.layerGroup(this.layerGroupList);
              airspaceLayer.addTo(this.map);
            }
            break;
        }
      },

      // 清空地图信息
      clearMapInfo(){
        this.clearAllLayer();
        airspaceLayer = null;
        pointLayer = null;
        lineLayer = null;
        this.airspacePointList = [];
        this.layerGroupList = [];
      },

      // websocket初始化
      initWebsocket(){
        var planeIcon = L.divIcon({
          html:'<img class="my-div-image" style="width:20px;height:20px;transform:rotate('+data.ang+'deg)" src="'+require("@/assets/images/airport.png")
          +'" /><div id="anum-'+data.anum+'" class="iconLabel" style="width:120px;padding:6px 10px;margin-top:-5px;color:'+(this.focusAnum&&this.focusAnum==data.anum?'#ae41f0':'#FFF')+';background-color:transparent;border-radius:5px;white-space:nowrap;display:'+(this.isShow?'block':'none')+'"><b>'+data.anum
          +'</b><br/>GV:'+(data.ang?data.ang:'-')+'°<br/>H:'+data.alt+'m<br/>S:'+(data.spd?data.spd:'-')+'km/h</div>',
          className: 'my-div-icon'
        });
        var marker;
        if(!data.anum){
          marker = L.marker([data.latGCJ02, data.lonGCJ02], {icon: planeIcon})
                .bindPopup("<div style='padding:5px;'><b>"+data.anum+"</b><br/>高度:"+data.alt+"m<br/>速度:"+(data.spd?data.spd:'-')+"km/h<br/>航向:"+(data.ang?data.ang:'-')+"°<br/>经纬度:"+Number(data.lat).toFixed(6)+","+Number(data.lon).toFixed(6)+"</div>");
          this.movingObj[data.anum+"Moving"] = marker;
          marker.addTo(this.map);
        }else{
          if(this.movingObj[data.anum+"Moving"]){
            this.movingObj[data.anum+"Moving"].setLatLng([data.latGCJ02, data.lonGCJ02]).bindPopup("<div style='padding:5px;'><b>"+data.anum+"</b><br/>高度:"+data.alt+"m<br/>速度:"+(data.spd?data.spd:'-')+"km/h<br/>航向:"+(data.ang?data.ang:'-')+"°<br/>经纬度:"+Number(data.lat).toFixed(6)+","+Number(data.lon).toFixed(6)+"</div>")
            .setIcon(planeIcon);
          }
        }
      },

      /* 
       * 绘制扇形
       * @params center 扇形中心点 Array [31.59586, 120.2995]
       * @params radius 扇形半径 Number
       * @params startArc 起始角度 Number -180-180 逆时针取值
       * @params stopArc 终止角度 Number -180-180 逆时针取值
       * @params pointNum 圆弧上点的个数 Number
      */
      getPoints(center, radius, startArc, stopArc, pointNum){
        var sin;
        var cos;
        var x;
        var y;
        var angle;
        var points = [];
        points.push(center);
        for (var i = 0; i <= pointNum; i++) {
            angle = Number(startArc) + (Number(stopArc) - Number(startArc)) * i / pointNum;
            sin = Math.sin(angle * Math.PI / 180);
            cos = Math.cos(angle * Math.PI / 180);
            y = center[0] + Number(radius) * cos;
            x = center[1] + Number(radius) * sin;
            points[i] = [y, x];
        }
        var point = points;
        point.push(center);
        return point;
      },
      drawSector(center, radius, startArc, stopArc, pointNum){
        var points = this.getPoints(center, radius, startArc, stopArc, pointNum);
        points[points.length] = points[0];
        sector = L.polygon(points, {color:"purple"}).addTo(this.map).bindPopup("(*^▽^*)").openPopup();
      },

      // 度转度分秒
      D2Dms (d_data = 0) {
        let degree = parseInt(d_data);
        let min = parseInt((d_data - degree) * 60);
        let sec = Math.round((d_data - degree) * 3600 - min * 60);
        return degree + "°" + min + "′" + sec + "″";
      },
    },
    beforeDestroy(){
      airspaceLayer = null;
      pointLayer = null;
      lineLayer = null;
      if(this.map){
        this.map = null;
        this.$parent.$refs.mapPart.map = null;
      }
    },
  }
</script>
<style scoped>
  #mainPart{
    width:100%;
    height:100vh;
    padding:0;
    overflow: hidden;
    position:relative;
  }
  /* 地图 */
  #map{
    width:100%;
    height:100%;
    padding:0;
    margin:0;
    position: relative;
  }
  /* 点位显示 */
  #currentPoint{
    height:30px;
    line-height:20px;
    font-size:14px;
    background: rgba(0, 0, 0, 0.5);
    color: #fff;
    border-radius: 4px;
    padding:5px 8px;
    margin:0;
    position:absolute;
    bottom:10px;
    right:10px;
    z-index:999;
  }

  /* 表格 */
  .el-table{
    width:calc(100% - 16px);
    font-size:13px;
    border:1px solid #243F63;
  }
  .el-table td, .el-table th, .el-table--small td, .el-table--small th{
    padding:4px 0!important;
    height:30px;
    padding:5px 0;
  }
  .el-table th, .el-table thead.is-group th, .el-table--small th{
    height: 30px!important;
    background-color:#063761!important;
    font-size:13px;
    color:#FFF;
    border:1px solid #063761;
  }
  .el-table thead.is-group th{
    border-bottom:1px solid #063761;
  }
  .el-table .cell{
    height:100%;
    line-height:29px;
    text-align:center;
    overflow: hidden;
    white-space: nowrap!important;
    text-overflow: ellipsis;
  }
  .el-table__body tr.current-row>td,
  .el-table--enable-row-hover .el-table__body tr:hover>td,
  .el-table__body tr.hover-row>td.el-table__cell,
  .el-table__body tr.el-table__row:hover td.el-table__cell{
    background-color: #156FA1!important;
    color: #FFF;
    cursor: pointer;
  }
  .el-table td .el-button{margin:0px!important;}
  .el-table td .el-button--text span{
    letter-spacing: 1px;
    border-bottom: 1px solid;
    padding-bottom:1px;
    margin: 0 3px;
  }
  .el-table--border:after, .el-table--group:after, .el-table:before{
    background-color:transparent!important;
  }
  .el-table, .el-table >>> th{
    color:#FFF;
    background-color:transparent;
    border:none!important;
    margin:0;
  }
  .el-table >>> th{
    border:none!important;
    background-color:#071629!important;
  }
  .el-table >>> th.el-table__cell, .el-table >>> td.el-table__cell{
    border:none!important;
  }
  .el-table >>> tbody tr:hover td{
    background-color:#0A1B31;
  }
  .el-table >>> tbody tr:nth-child(odd){
    background-color:#0A1B31;
  }
  .el-table >>> tbody tr:nth-child(even){
    background-color:#071629;
  }
  .el-table >>> .el-table__header-wrapper th,
  .el-table >>> .el-table__fixed-header-wrapper th{
    background-color:#000A2E;
    border:none!important;
    color:#e6dede;
  }
  .el-table >>> td.el-table__cell, .el-table >>> th.el-table__cell.is-leaf{
    border:none!important;
    background-color:transparent;
    line-height:29px;
  }
</style>